﻿using UnityEngine;
using System.Collections;

public class CharacterAnimator : MonoBehaviour {
	
	public CharacterAnimation curAnimation;
	public int facing; // 1 - right, -1 - left
	public int curSprite;
	public bool isPlaying;
	public bool playReverse;

	private SpriteRenderer _spriteRenderer;
	private float _animSpeed;
	private float _animTimer;
	
	// Use this for initialization
	void Start () {
		_spriteRenderer = renderer as SpriteRenderer;
		curSprite = 0;
		facing = 1;
		isPlaying = false;
		_animTimer = 0.0f;
		if (curAnimation != null) {
			_animSpeed = 1 / curAnimation.framesPerSecond;
		}
		
	}
	
	// Update is called once per frame
	void Update () {
		if(curAnimation != null) {
			_animTimer += Time.deltaTime;
			if(_animTimer >= _animSpeed) {
				if(playReverse) {
					NextSpriteReverse();
				} else {
					NextSpriteForward();
				}
			}
			_spriteRenderer.sprite = curAnimation.sprites [curSprite];
		}
	}

	void NextSpriteForward() {
		++curSprite;
		_animTimer = 0.0f;
		if(curSprite >= curAnimation.sprites.Length) {
			if(curAnimation.isLooping) {
				curSprite = 0;
			} else {
				curSprite = curAnimation.sprites.Length-1;
				isPlaying = false;
			}
		}
	}

	void NextSpriteReverse() {
		--curSprite;
		_animTimer = 0.0f;
		if(curSprite <= 0) {
			if(curAnimation.isLooping) {
				curSprite = curAnimation.sprites.Length-1;
			} else {
				curSprite = 0;
				isPlaying = false;
			}
		}
	}

	public void ChangeAnimation(CharacterAnimation animation, int flip, bool reverse = false) {
		playReverse = reverse;

		if(curAnimation != animation || !isPlaying) {
			curAnimation = animation;
			curSprite = 0;
			_animSpeed = 1/animation.framesPerSecond;
			_animTimer = 0.0f;
			isPlaying = true;

			if (playReverse) {
				curSprite = animation.sprites.Length-1;
			}
		}


		FlipAnimation (flip);
	}

	// flip: 0 = no flip, 1 = face right, 2 = face left, 3 = switch
	public void FlipAnimation(int flip) {
		if(flip == 1) {
			Vector3 temp = _spriteRenderer.transform.localScale;
			temp.x = Mathf.Abs(temp.x);
			_spriteRenderer.transform.localScale = temp;
			facing = 1;
		} else if(flip == 2) {
			Vector3 temp = _spriteRenderer.transform.localScale;
			temp.x = -Mathf.Abs(temp.x);
			_spriteRenderer.transform.localScale = temp;
			facing = -1;
		} else if(flip == 3) {
			Vector3 temp = _spriteRenderer.transform.localScale;
			temp.x = -temp.x;
			_spriteRenderer.transform.localScale = temp;
			facing *= -1;
		}
	}

	public void Rotate(float degrees) {
		transform.Rotate (0.0f, 0.0f, degrees);
	}
}
